<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>遍历器对象的return()和throw()</title>
</head>
<body>
    <h1>遍历器对象的return()和throw()</h1>

    <script>
        // 部署return方法的例子
        function* numbers() {
            yield 1;
            try {
                yield 2;
                yield 3;
            } finally {
                console.log('Generator执行完毕');
            }
            yield 4;
        }

        const g = numbers();
        console.log(g.next()); // { value: 1, done: false }
        console.log(g.return('结束')); // Generator执行完毕 
                                      // { value: "结束", done: true }

        // 自定义Iterator的return方法
        const myIterator = {
            data: ['a', 'b', 'c'],
            [Symbol.iterator]() {
                const self = this;
                let index = 0;
                return {
                    next() {
                        if (index < self.data.length) {
                            return {
                                value: self.data[index++],
                                done: false
                            };
                        }
                        return { value: undefined, done: true };
                    },
                    return() {
                        console.log('提前退出遍历');
                        return { value: undefined, done: true };
                    }
                };
            }
        };

        // break语句触发return方法
        for (let value of myIterator) {
            console.log(value);
            if (value === 'b') break;
        }
    </script>
</body>
</html> 